package com.jamlu.framework.album;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.isseiaoki.simplecropview.CropImageView;
import com.isseiaoki.simplecropview.callback.LoadCallback;
import com.jamlu.framework.R;

import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;

/**
 * Created by DMing at 2018/1/2 0002
 */

public class PhotoCropWindow extends PopupWindow {

    private CropImageView mCropView;
    private ImageView mIvResult;
    private Uri picUri;
    private Bitmap commitBp;
    private PhotoCropCallBack photoCropCallBack;


    @SuppressLint("RestrictedApi")
    public PhotoCropWindow(Context context) {
        super(context);
        @SuppressLint("InflateParams") View viewGroup = LayoutInflater.from(context).inflate(R.layout.layout_activity_base, null);
        Toolbar mToolbar = viewGroup.findViewById(com.jamlu.framework.R.id.toolbar);
        mToolbar.setTitle("");
        mToolbar.setNavigationIcon(com.jamlu.framework.R.drawable.ic_back_white); //设置返回按钮图标
        mToolbar.setBackgroundResource(R.drawable.bg_top_menu);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mToolbar.inflateMenu(R.menu.titlebar_menu);
        MenuItem mItem = mToolbar.getMenu().findItem(R.id.item);
        mItem.setTitle(R.string.txt_select_done);
        mItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                onCommitBtn();
                return true;
            }
        });
        View title = viewGroup.findViewById(R.id.vs_title);
        if (title instanceof ViewStub) {
            ViewStub titleSub = (ViewStub) title;
            titleSub.setLayoutResource(R.layout.layout_title_textview);
            titleSub.inflate();
            TextView  mTvTitle = viewGroup.findViewById(com.jamlu.framework.R.id.tv_title);
            mTvTitle.setText(R.string.txt_crop);
        }
        //生成内容布局
        ViewStub viewStub = viewGroup.findViewById(com.jamlu.framework.R.id.vs_content);
        viewStub.setLayoutResource(R.layout.activity_crop);
        viewStub.inflate();

        setContentView(viewGroup);
        initView(viewGroup);
        setAnimationStyle(R.style.popupWindow_null_anim_style);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        setBackgroundDrawable(dw);
        setOutsideTouchable(true);
    }

    public void setPicModeListener(Uri picUri,CropImageView.CropMode cropMode,PhotoCropCallBack photoCropCallBack){
        this.photoCropCallBack = photoCropCallBack;
        Log.i("Photo Crop","picUri: "+picUri);
        mCropView.setCompressFormat(Bitmap.CompressFormat.JPEG);
        mCropView.setCompressQuality(90);
        mCropView.setCropMode(cropMode);
        mCropView.setInitialFrameScale(0.75f);
        mCropView.setGuideShowMode(CropImageView.ShowMode.SHOW_ON_TOUCH);
        mCropView.load(picUri).useThumbnail(true).execute(new LoadCallback() {
            @Override
            public void onSuccess() {
                Log.i("Photo Crop","CropImageView onSuccess");
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showShort(mCropView.getContext().getString(R.string.txt_pic_load_failure));
                dismiss();
            }
        });
    }

    private void onCommitBtn() {
        if (commitBp != null) {
            commitData();
            return ;
        }
        if (mCropView.isCropping())return ;
        if (mCropView.isSaving())return ;
//        mCropView.crop(PhotoCropWindow.this.picUri)
//                .outputMaxHeight(600)
//                .outputMaxWidth(600)
//                .execute(new CropCallback() {
//                    @Override public void onSuccess(Bitmap cropped) {
//                    }
//
//                    @Override public void onError(Throwable e) {
//                        ToastUtils.show("图像裁剪失败");
//                    }
//                });
        mCropView.crop(PhotoCropWindow.this.picUri)
                .outputMaxHeight(600)
                .outputMaxWidth(600)
                .executeAsSingle()
                .subscribe(new SingleObserver<Bitmap>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(Bitmap bitmap) {
                        commitBp = bitmap;
                        if (commitBp != null) {
                            mCropView.setVisibility(View.GONE);
                            PhotoCropWindow.this.getContentView().findViewById(R.id.ll_rotate).setVisibility(View.GONE);
                            mIvResult.setImageBitmap(commitBp);
                            commitData();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showShort("图像裁剪失败");
                    }
                });
    }

    protected void initView(View view) {
        mCropView = view.findViewById(R.id.cropImageView);
        mIvResult = view.findViewById(R.id.iv_result);
        view.findViewById(R.id.iv_rotate_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_M90D);
            }
        });
        view.findViewById(R.id.iv_rotate_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
            }
        });
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                onDestroy();
                Log.e("Photo Crop","onDismiss!!!!");
            }
        });
    }


    private void commitData(){
        if (photoCropCallBack != null)photoCropCallBack.PhotoBitmap(commitBp);
    }


    protected void onDestroy() {
        if (commitBp != null && !commitBp.isRecycled()){
            commitBp.recycle();
            commitBp = null;
        }
        this.photoCropCallBack = null;
        this.picUri = null;
    }

    public interface PhotoCropCallBack{
        void PhotoBitmap(Bitmap bitmap);
    }
}
